package com.corpgovernment.common.utils;

import cn.hutool.core.collection.CollectionUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 切割List
 * @param <T>
 */
public class CutListUtils<T> {

    /**
     * 切割List集合
     * @param list 需要切割的集合
     * @param cutNum 每个集合需要的大小，如10000条数据每页需要1000则传入1000
     * @return
     */
    public static <T> Map<Integer, List<T>> cutList(List<T> list, Integer cutNum){
        Map<Integer, List<T>> result = new HashMap<>();
        //集合大小
        Integer count = list.size();
        //集合大小
        Integer taskNum = count/cutNum;
        //集合大小取余大于0说明需要多一次循环
        if (count%cutNum > 0){
            taskNum += 1;
        }
        //当前切割总大小
        Integer totalCutNum = 0;
        //循环切割
        for (int i = 0; i < taskNum; i ++){
            //避免下标越界
            Integer onCutNum = totalCutNum + cutNum;
            if (onCutNum > count){
                onCutNum = count;
            }
            //存入map
            result.put(i, CollectionUtil.newArrayList(list.subList(totalCutNum, onCutNum)));
            totalCutNum += cutNum;
        }
        //返回
        return result;
    }

}
